package com.hzw.video.muxer

import android.media.MediaCodec
import android.media.MediaFormat
import android.media.MediaMuxer
import android.os.Environment
import android.util.Log
import com.blankj.utilcode.util.TimeUtils
import java.nio.ByteBuffer

/**
 *
 * @Author:         HuaZhongWei
 * @CreateDate:     2020/9/18 16:37
 *
 * @Description:
 *
 */
class MMuxer(val path: String) {

    companion object {
        const val TAG = "MMuxer"
    }


    private var mediaMuxer: MediaMuxer = MediaMuxer(path, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4)

    private var videoTrackIndex = -1
    private var audioTrackIndex = -1

    private var isAudioTrackAdd = false
    private var isVideoTrackAdd = false

    private var isStart = false

    fun addVideoTrack(format: MediaFormat) {
        videoTrackIndex = mediaMuxer.addTrack(format)
        isVideoTrackAdd = true
        startMuxer()
    }

    fun addAudioTrack(format: MediaFormat) {
        audioTrackIndex = mediaMuxer.addTrack(format)
        isAudioTrackAdd = true
        startMuxer()
    }

    fun setNoAudio() {
        if (isAudioTrackAdd) {
            return
        }

        isAudioTrackAdd = true
        startMuxer()
    }

    fun setNoVideo() {
        if (isVideoTrackAdd) {
            return
        }

        isVideoTrackAdd = true
        startMuxer()
    }

    private fun startMuxer() {
        if (isAudioTrackAdd && isVideoTrackAdd) {
            mediaMuxer.start()
            isStart = true
        }
    }

    fun writeVideoData(byteBuffer: ByteBuffer, bufferInfo: MediaCodec.BufferInfo) {
        if (isStart) {
            mediaMuxer.writeSampleData(videoTrackIndex, byteBuffer, bufferInfo)
        }
    }

    fun writeAudioData(byteBuffer: ByteBuffer, bufferInfo: MediaCodec.BufferInfo) {
        if (isStart) {
            mediaMuxer.writeSampleData(audioTrackIndex, byteBuffer, bufferInfo)
        }
    }

    fun release() {
        isAudioTrackAdd = false
        isVideoTrackAdd = false
        mediaMuxer.stop()
        mediaMuxer.release()
    }
}